<?php
namespace Plugin;

class WxApp
{
    public static $appId     = "wxc56176gg1977cf14";
    public static $appSecret = "4b9cd46cc46f3042e6f3fb6c7dd8ad6";
    public static $timeout   = 30; //超时

    /*数据解密*/
    public static function DeCode($encryptedData, $sessionKey, $iv)
    {
        if (strlen($sessionKey) != 24) {
            return ["state" => "error", "msg" => "sessionKey不合法"];
        }
        if (strlen($iv) != 24) {
            return ["state" => "error", "msg" => "iv不合法"];
        }
        $sessionKey    = base64_decode($sessionKey);
        $encryptedData = base64_decode($encryptedData);
        $iv            = base64_decode($iv);
        $data          = openssl_decrypt($encryptedData, "AES-128-CBC", $sessionKey, 1, $iv);
        $data          = json_decode($data, true);
        if ($data == null) {
            return ["state" => "error", "msg" => "数据为空"];
        }
        if ($data['watermark']['appid'] != self::$appId) {
            return ["state" => "error", "msg" => "appId不合法"];
        }
        return ["state" => "ok", "msg" => "解密成功", "data" => $data];
    }
    /*登录凭证校验*/
    public static function Code2Session($code)
    {
        $url  = "https://api.weixin.qq.com/sns/jscode2session";
        $data = [
            "appid"      => self::$appId,
            "secret"     => self::$appSecret,
            "js_code"    => $code,
            "grant_type" => "authorization_code",
        ];
        return self::http($url, $data);
    }

    /*请求数据*/
    private static function http($url, $data, $httpType = 'GET')
    {
        $curl = curl_init();
        if ($httpType == 'GET') {
            $url = $url . '?' . http_build_query($data);
        } else {
            curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, self::$timeout);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            $data = ["state" => "error", "msg" => "请求异常"];
        } else {
            $data = ["state" => "ok", "msg" => "请求成功", "data" => json_decode($data, true)];
        }
        curl_close($curl);
        return $data;
    }
}
